package org.hghog.jlinkdemo.util;

import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import org.hghog.jlinkdemo.controller.HelloController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author : HGhog
 * @date : 2024-08-29 19:53
 * @version: 1.0
 */
public final class DefaultPath extends HelloController {

    private final static String PROJECT_DIR = System.getProperty("user.dir");
    private final static String FILE_NAME = "DEFAULT_CONFIG.init";

    private final static String IN_PATH_ID = "inText";
    private final static String OUT_PATH_ID = "outText";

    static {
        File file = new File(PROJECT_DIR + File.separator + FILE_NAME);
        if (file.exists()) {
            try (InputStream in = new FileInputStream(file)) {
                String config = new String(in.readAllBytes(), StandardCharsets.UTF_8);

                info.setInPath(config.split("\n")[0]);
                info.setOutPath(config.split("\n")[1]);
            } catch (Exception e) {
                System.out.println("获取上次设置目录失败！！！");
            }
        }
    }

    private DefaultPath() {
    }

    public static void saveLastTimePath() {
        // 设置上一次路径
        File config = new File(PROJECT_DIR + File.separator + FILE_NAME);
        if (config.exists()) {
            boolean delete = config.delete();
            if (!delete) {
                System.out.println("默认目录设置失败！！！");
                return;
            }
        }
        try {
            boolean newFile = config.createNewFile();
            if (!newFile) {
                System.out.println("默认目录设置失败！！！");
                return;
            }
            FileOutputStream outStream = new FileOutputStream(config);
            String configStr = info.getInPath() + "\n" + info.getOutPath();
            outStream.write(configStr.getBytes(StandardCharsets.UTF_8));
            outStream.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static void initLastTimePath(ObservableList<Node> nodes) {
        for (Node node : nodes) {
            if (node instanceof Text) continue;
            Parent parent = (Parent) node;
            if (IN_PATH_ID.equals(parent.getId())) {
                TextField textField = (TextField) parent;
                textField.setText(info.getInPath());
            }
            if (OUT_PATH_ID.equals(parent.getId())) {
                TextField textField = (TextField) parent;
                textField.setText(info.getOutPath());
            }
            if (!parent.getChildrenUnmodifiable().isEmpty()) {
                initLastTimePath(parent.getChildrenUnmodifiable());
            }
        }
    }
}
